from flask_jwt_extended import create_access_token

from takeaway import resp
from takeaway.store import user as store
from takeaway.schema import user as schema


def add_user(data):
    user = store.select_user_by_phone(phone=data["phone"])
    if user:
        return resp.make_fail(msg="phone already exists")

    user = store.insert_user(data)
    return resp.make_success(data=schema.User().dump(user))


def login(data):
    user = store.select_user_by_phone(phone=data["phone"])
    if user and user.validate_password(data["password"]):
        return resp.make_success(data=create_access_token(user.id))
    return resp.make_fail(msg="incorrect password")


def get_user(id_):
    return store.select_user_by_id(id_)
